﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Caching;

namespace PracticeAzure.Website.Shared
{
    public class InProcCache : ICache
    {
        private MemoryCache _cache;

        public InProcCache()
        {
            _cache = MemoryCache.Default;
        }

        public T Get<T>(string key)
        {
            var value = _cache.Get(key);
            try
            {
                return (T)value;
            }
            catch
            {
                // no need to do anything just return null to indecate cache missing
                return default(T);
            }
        }

        public void Add<T>(string key, T value, TimeSpan expiration)
        {
            _cache.Add(key, value, 
                new CacheItemPolicy() 
                { 
                    AbsoluteExpiration = DateTimeOffset.Now.AddTicks(expiration.Ticks) 
                });
        }

        public void Clear()
        {
            _cache.All((kvp) =>
                {
                    _cache.Remove(kvp.Key);
                    return true;
                });
        }
    }
}